// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()


const db = cloud.database()
const MAX_LIMIT = 20

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  // const countResult = await db.collection('bills').where({
    // _openid: wxContext.OPENID
  // }).count()
  //const total = countResult.total
  //const batchTimes = Math.ceil(total / 50)
  const bills = []
  const pageSize = event.pageSize > MAX_LIMIT ? MAX_LIMIT : event.pageSize
  //
  //for (let i = 0; i < batchTimes; i++) {
    const promise = db.collection('bills').where({
      _openid: wxContext.OPENID
    }).orderBy('createDate', 'desc').skip((event.pageNum - 1) * pageSize).limit(pageSize).get()
    bills.push(promise)
  //}
  // 等待所有
  return (await Promise.all(bills)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      //errMsg是信息不一定是错误信息，正常时候的信息也存储在这
      errMsg: acc.errMsg,
    }
  })
}